<script setup lang="tsx">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { DataSourceConfig, DataSourceConfigEditAndCreateParams } from '@/service/api';
import { DbDriverMap, DbUrlMap, createDataSourceConfig, dbTestConnection, updateDataSourceConfig } from '@/service/api';
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict';

defineOptions({
  name: 'DatasourceOperateModal'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: DataSourceConfig | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.base.datasource.add'),
    edit: $t('page.base.datasource.edit')
  };
  return titles[props.operateType];
});

type Model = Pick<
  DataSourceConfigEditAndCreateParams,
  'name' | 'code' | 'remark' | 'dbType' | 'dbDriver' | 'dbUrl' | 'dbName' | 'dbUsername' | 'dbPassword'
> & {
  id: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    name: '',
    code: '',
    remark: '',
    dbType: null,
    dbDriver: '',
    dbUrl: '',
    dbName: '',
    dbUsername: '',
    dbPassword: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'code' | 'dbType' | 'dbDriver' | 'dbUrl' | 'dbUsername' | 'dbPassword'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  code: defaultRequiredRule,
  dbType: defaultRequiredRule,
  dbDriver: defaultRequiredRule,
  dbUrl: defaultRequiredRule,
  dbUsername: defaultRequiredRule,
  dbPassword: defaultRequiredRule
};

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    // request
    const { error } = await updateDataSourceConfig(model.id as number, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createDataSourceConfig(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (!props.rowData) return;

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function handleDbTypeUpdateValue(value: string) {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-expect-error
  model.dbDriver = DbDriverMap[value].dbDriver.toString();
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-expect-error
  model.dbUrl = DbUrlMap[value].dbUrl.toString();
}

async function handleTestConnectionClick() {
  const { data } = await dbTestConnection(model);
  if (data) {
    window.$message?.success($t('page.base.datasource.testConnectionSuccess'));
  } else {
    window.$message?.error($t('page.base.datasource.testConnectionFail'));
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" :mask-closable="false" class="w-250">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto">
        <NFormItem :label="$t('page.base.datasource.code')" path="code">
          <NInput v-model:value="model.code" :placeholder="$t('page.base.datasource.form.code')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.datasource.name')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.base.datasource.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.datasource.dbType')" path="dbType">
          <NSelect
            v-model:value="model.dbType"
            :placeholder="$t('page.base.datasource.form.dbType')"
            :options="getStrDictOptions(DICT_TYPE.SYSTEM_DATASOURCE_TYPE)"
            clearable
            @update:value="handleDbTypeUpdateValue"
          />
        </NFormItem>
        <NFormItem :label="$t('page.base.datasource.dbDriver')" path="dbDriver">
          <NInput v-model:value="model.dbDriver" :placeholder="$t('page.base.datasource.form.dbDriver')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.datasource.dbUrl')" path="dbUrl">
          <NInput v-model:value="model.dbUrl" :placeholder="$t('page.base.datasource.form.dbUrl')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.datasource.dbUsername')" path="dbUsername">
          <NInput v-model:value="model.dbUsername" :placeholder="$t('page.base.datasource.form.dbUsername')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.datasource.dbPassword')" path="dbPassword">
          <NInput
            v-model:value="model.dbPassword"
            type="password"
            show-password-on="click"
            :placeholder="$t('page.base.datasource.form.dbPassword')"
          />
          <NButton type="primary" class="ml-2 w-20%" @click="handleTestConnectionClick">
            {{ $t('page.base.datasource.testConnection') }}
          </NButton>
        </NFormItem>
        <NFormItem :label="$t('page.base.datasource.remark')" path="remark">
          <NInput v-model:value="model.remark" type="textarea" :placeholder="$t('page.base.datasource.form.remark')" />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
